import {
	baseUrl
} from "./config.js"
let downLoadFile = new class {
	// 下载文件工具

	constructor() {
		this._baseUrl = baseUrl; //后端环境地址
		this._platform = uni.$u.platform //平台类型
		switch (this._platform) {
			case 'plus':
				this._saveRootUrl = '_doc'
				break
			case 'mp':
			case 'wx':
				this._saveRootUrl = wx.env.USER_DATA_PATH
				this._fileSystemManager = uni.getFileSystemManager() //定义全局唯一的文件管理器
				break
		}
		this._parentUrl = 'cnde_save'; //自定义保存文件的父级文件夹，若没有，则创建
		this._savePath = this._saveRootUrl + '/' + this._parentUrl + '/'; //保存文件的完整路径
		this._downloadUrl = baseUrl + "/attachInfo/fileDownload"; //下载地址
	}


	async download(param) {
		let res;
		if (param.fileArr && param.fileArr.length > 0) {
			for (let i = 0; i < param.fileArr.length; i++) {
				// console.log(param.fileArr[i].url)
				let fName = param.fileArr[i].name ? param.fileArr[i].name : ''
				res = await this.uniDownload(this._baseUrl + param.fileArr[i].url, fName)
			}
		} else {
			let downUrl = this._downloadUrl + '?id=' + param.id + '&type=' + param.type
			res = await this.uniDownload(downUrl, param.fileName)
		}
		
		return res;
	}
	async uniDownload(downUrl, fileName) {
		let me = this;
		let downloadTask;
		if (await me.isSaved(fileName)) {
			// me.openFile(me._savePath + fileName)
			const FileShare= uni.requireNativePlugin('life-FileShare');
			FileShare.render({
			        type:"WX",//QQ为QQ，微信为WX，系统默认是SYSTEM，不填写默认SYSTEM
			        filePath:plus.io.convertLocalFileSystemURL(me._savePath + fileName),
			}, result => {
							
			}
			);
			return
		}
		downloadTask = uni.downloadFile({
			url: downUrl,
			success: (res) => {
				if (res.statusCode === 200) {
					console.log('下载成功');
				}
				if (me._platform == 'plus') {
					me.handleFile_APP(res.tempFilePath, fileName)
				} else if (me._platform == 'mp' || me._platform == 'weixin') {
					me.handleFile_WEIXIN(res.tempFilePath, fileName)
				}
			}
		});
		downloadTask.onProgressUpdate((res) => {
			// console.log('下载进度' + res.progress);
			// console.log('已经下载的数据长度' + res.totalBytesWritten);
			// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
		}, (err) => {
			console.log(err)
		});
	}
	handleFile_APP(tempFilePath, fileName) {
		let me = this;
		console.log(tempFilePath)
		console.log(fileName)
		console.log(me._saveRootUrl)
		console.log(me._parentUrl)
		// APP平台下，创建“保存”文件夹，并把下载文件复制到该文件夹
		plus.io.resolveLocalFileSystemURL(tempFilePath, (srcEntry) => {
			plus.io.resolveLocalFileSystemURL(me._saveRootUrl, (
				dstEntry) => {
				dstEntry.getDirectory(me._parentUrl, {
					create: true,
					exclusive: false
				}, (saveEntry) => {
					console.log(fileName)
					console.log("saveEntry.toURL", saveEntry.toURL())
					srcEntry.copyTo(
						saveEntry,
						fileName,
						(res) => {
							const savedFilePath = res.toURL()
							me.openFile(savedFilePath)
						}, (
							err
						) => {
							console
								.log(
									err
								)
						});

				})
			}, (err) => {
				uni.showToast({
					title: '下载失败',
					duration: 2000
				});
			})
		});
	}
	handleFile_WEIXIN(tempFilePath, fileName) {
		// 微信小程序平台下，创建“保存”文件夹，并把下载文件复制到该文件夹
		let me = this
		let has_parentUrl = false //判断是否有父级文件夹
		try {
			console.log(`${wx.env.USER_DATA_PATH+'/'+me._parentUrl}`)
			me._fileSystemManager.accessSync(`${wx.env.USER_DATA_PATH+'/'+me._parentUrl}`)
			has_parentUrl = true
		} catch (e) {
			has_parentUrl = false
			console.error('检查文件是否存在：', e)
		}
		try {
			if (!has_parentUrl) {
				me._fileSystemManager.mkdirSync(wx.env.USER_DATA_PATH + '/' + me._parentUrl)
			}
			me._fileSystemManager.saveFile({
				tempFilePath: tempFilePath,
				filePath: wx.env.USER_DATA_PATH + '/' + me._parentUrl + '/' + fileName,
				success: function(res) {
					me.openFile(res.savedFilePath)
				},
				fail: function(err) {
					console.log('保存文件:', err)
				}
			});
		} catch (e) {
			console.error('创建父级文件:', err)
		}
	}
	async isSaved(fileName) {
		// 根据文件名判断是否将该文件保存
		let me = this
		let promise
		if (me._platform == 'plus') {
			promise = new Promise((resolve, reject) => {
				plus.io.resolveLocalFileSystemURL(
					me._savePath + fileName, (res) => {
						// console.log('已经存在该文件')
						resolve(true)
					}, (err) => {
						reject(false)
					})
			})

		} else if (me._platform == 'mp' || me._platform == 'weixin') {
			promise = new Promise((resolve, reject) => {
				me._fileSystemManager.access({
					path: me._savePath + fileName,
					success: function(res) {
						resolve(true)
					},
					fail: function(err) {
						reject(false)
					}
				})
			})
		}
		let rs = await promise.then(res => {
			return res
		}).catch(err => {
			return err
		})
		return rs
	}
	openFile(path) {
		console.log(path)
		uni.openDocument({
			filePath: path,
			// fileType:'doc',
			showMenu: true,
			success: function() {
				console
					.log(
						'打开文档成功'
					);
			},
			fail(
				err
			) {
				console.log(err)
				uni.showToast({
					title: '打开文档失败',
					duration: 2000
				});
				// console.log("打开失败" + JSON.stringify(err))
			}
		});
	}
	deleteFile(fileName) {
		let me = this
		uni.removeSavedFile({
			filePath: me._savePath + fileName,
			complete: function(res) {
				console.log(res);
			}
		});
	}
}

export {
	downLoadFile
}
